/*
 * @copyright 2010 Gerald Jacobson
 * @license GNU General Public License
 * 
 * This file is part of My Quick Rules.
 *
 * My Quick Rules is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * My Quick Rules is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with My Quick Rules.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.amphiprion.myquickrules.task;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.amphiprion.myquickrules.R;
import org.amphiprion.myquickrules.dao.VersionDao;
import org.amphiprion.myquickrules.entity.LocalGame;
import org.amphiprion.myquickrules.entity.Version;
import org.amphiprion.myquickrules.util.ApplicationConstants;
import org.amphiprion.myquickrules.util.ConfigUtil;
import org.amphiprion.myquickrules.util.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

/**
 * @author amphiprion
 * 
 */
public class ImportGameRuleTask extends AsyncTask<Void, Integer, Boolean> {
	private ProgressDialog progress;
	private String title;
	private ImportRuleListener caller;
	private LocalGame game;
	private String ruleId;

	/**
	 * Default constructor.
	 */
	public ImportGameRuleTask(ImportRuleListener caller, LocalGame game) {
		this.caller = caller;
		this.game = game;
		ruleId = game.getId();
		title = game.getName();
	}

	/**
	 * Default constructor.
	 */
	public ImportGameRuleTask(ImportRuleListener caller, String ruleId) {
		this.caller = caller;
		this.ruleId = ruleId;
		title = "";
	}

	@Override
	protected Boolean doInBackground(Void... v) {
		try {
			if (game == null) {
				// retrieve information from repository (its a manual update)
				publishProgress(R.string.import_step_retrieve_remote_info, 0, 0);
				String url = ConfigUtil.getVersionInformationUrl(ruleId);
				Version vers = VersionDao.getInstance().getVersionInformation(url);
				if (vers == null) {
					return Boolean.FALSE;
				}
				game = new LocalGame();
				game.setId(vers.id);
				game.setName(vers.gameName);
				game.length = vers.length;
				game.resolution = vers.resolution;
				game.version = vers.version;
				game.creator = vers.creator;
				game.mail = vers.mail;
				title = game.getName();
			}
			publishProgress(R.string.import_step_read_database, 0, 0);
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/games.xml");
			InputStream is = new FileInputStream(f);

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);
			is.close();
			NodeList list = document.getElementsByTagName("game");
			Element existingNode = null;
			for (int i = 0; i < list.getLength(); i++) {
				Element gameNode = (Element) list.item(i);
				String id = gameNode.getAttributes().getNamedItem("id").getNodeValue();
				if (game.getId().equals(id)) {
					existingNode = gameNode;
					break;
				}
			}

			Element newChild = document.createElement("game");
			newChild.setAttribute("id", game.getId());
			newChild.setAttribute("resolution", game.resolution);
			newChild.setAttribute("version", game.version);
			Element newName = document.createElement("name");
			newChild.appendChild(newName);
			Element newLang = document.createElement("lang");
			newLang.appendChild(document.createTextNode(game.getName()));
			newName.appendChild(newLang);

			if (existingNode != null) {
				document.getElementsByTagName("games").item(0).replaceChild(newChild, existingNode);
			} else {
				document.getElementsByTagName("games").item(0).appendChild(newChild);
			}
			publishProgress(R.string.import_step_zip, 0, game.length);
			File backup = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/games.xml.sav");
			try {
				URL url = new URL(ConfigUtil.getRulePackUrl(game.getId()));
				URLConnection con = url.openConnection();
				InputStream pis = con.getInputStream();
				File zip = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/" + game.getId() + ".zip");
				OutputStream pos = new FileOutputStream(zip);
				byte[] b = new byte[4096];
				int len = 0;
				int totalLen = 0;
				while ((len = pis.read(b)) > 0) {
					totalLen += len;
					pos.write(b, 0, len);
					publishProgress(R.string.import_step_zip, totalLen, game.length);
				}
				pos.close();
				pis.close();

				// UNZIP
				publishProgress(R.string.import_step_unzip, 0, 0);
				XMLUtil.unzip(zip, Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY);

				zip.delete();

				publishProgress(R.string.import_step_write_database, 0, 0);
				backup.delete();
				f.renameTo(backup);
				XMLUtil.writeDocument(document, f);
				// download files pack

				backup.delete();
				publishProgress(R.string.ok, 0, 0);
				return Boolean.TRUE;
			} catch (Exception e) {
				f.delete();
				backup.renameTo(f);
				Log.e(ApplicationConstants.PACKAGE, "", e);
				return Boolean.FALSE;
			}
		} catch (Exception e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			return Boolean.FALSE;
		}
	}

	@Override
	protected void onPreExecute() {
		progress = ProgressDialog.show(caller.getContext(), "...", "...", true, true, new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				cancel(true);
				caller.importEnded(false, null);
			}
		});
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		progress.setTitle(title);
		progress.setMessage(caller.getContext().getResources().getString(values[0], values[1], values[2]));
	}

	@Override
	protected void onPostExecute(Boolean succeed) {
		progress.cancel();
		caller.importEnded(!isCancelled() && succeed, game);

	}

	public interface ImportRuleListener {
		void importEnded(boolean succeed, LocalGame newGame);

		Context getContext();
	}

}
